<template>
    <div class="import-modal-wrapper">
        <el-dialog :model-value="props.value" :title="dialog.title" :width="dialog.width" destroy-on-close>
            <ul class="import-modal-box">
                <li>
                    <span>请使用系统提供的Excel模版导入协议内容：</span>
                    <el-button link type="primary" @click="onDownload" :loading="downLoading"> 下载 </el-button>
                </li>
                <li>
                    <span>协议内容文件：</span>
                    <el-upload :http-request="onImport" :show-file-list="false" style="display: flex; margin: 0 10px">
                        <el-button link type="primary" :loading="impLoading"> 上传 </el-button>
                    </el-upload>
                </li>
            </ul>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="closeDialog">关闭</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { IoTProtocolService } from '@great/services';
import { reactive } from 'vue';
import type { PopupBoxProps } from '@great/utils';
import type { UploadRequestHandler, UploadRequestOptions } from 'element-plus';

interface IProps extends PopupBoxProps {
    protocolNo: string;
    callBack?: () => Promise<void>;
}
const props = defineProps<IProps>();

interface Dialog {
    title: string;
    width: number;
    detail?: Record<string, any>;
}
const dialog = reactive<Dialog>({
    title: '导入Modbus协议内容',
    width: 600,
    detail: undefined
});
const downLoading = ref(false);
const impLoading = ref(false);

// 导入
const onImport: UploadRequestHandler = async (opt: UploadRequestOptions) => {
    impLoading.value = true;
    const formData = new FormData();
    formData.append('file', opt.file);
    await IoTProtocolService.importProtocolContent(props.protocolNo, formData);
    ElNotification({
        title: '导入成功！',
        type: 'success'
    });
    impLoading.value = false;
};

const onDownload = async () => {
    downLoading.value = true;
    await IoTProtocolService.downloadProtocolTemplate(props.protocolNo);
    downLoading.value = false;
};
//关闭弹框
const closeDialog = () => {
    props.close();
    props.callBack?.();
};
</script>
<style scoped lang="scss">
.import-modal-wrapper {
    .import-modal-box {
        li {
            list-style: none;
            line-height: 40px;
            display: flex;
        }
    }
}
</style>
